//
//  HZUnCatchExceptionHandler.m
//  app
//
//  Created by 刘华舟 on 15/4/27.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HZUnCatchExceptionHandler.h"

NSString * const HZUncaughtExceptionHandlerSignalExceptionName = @"HZUncaughtExceptionHandlerSignalExceptionName";
NSString * const HZUncaughtExceptionHandlerSignalKey = @"HZUncaughtExceptionHandlerSignalKey";
NSString * const HZUncaughtExceptionHandlerAddressesKey = @"HZUncaughtExceptionHandlerAddressesKey";

#define kHZCrashConsoleLogFilePath [NSHomeDirectory() stringByAppendingString:@"/Library/Caches/console.log"]
#define kHZCrashLogFilePath kCrashLogFilePath

volatile int32_t HZUncaughtExceptionCount = 0;
const int32_t HZUncaughtExceptionMaximum = 10;

const NSInteger HZUncaughtExceptionHandlerSkipAddressCount = 4;
const NSInteger HZUncaughtExceptionHandlerReportAddressCount = 5;

@implementation HZUnCatchExceptionHandler

//获取错误栈信息
+ (NSArray *)backtrace
{
    void* callstack[128];
    int frames = backtrace(callstack, 128);
    char **strs = backtrace_symbols(callstack, frames);
    
    int i;
    NSMutableArray *backtrace = [NSMutableArray arrayWithCapacity:frames];
    for (
         i = HZUncaughtExceptionHandlerSkipAddressCount;
         i < HZUncaughtExceptionHandlerSkipAddressCount +
         HZUncaughtExceptionHandlerReportAddressCount;
         i++)
    {
        [backtrace addObject:[NSString stringWithUTF8String:strs[i]]];
    }
    free(strs);
    
    return backtrace;
}


#pragma mark 处理已经捕获的异常
- (void)handleException:(NSException *)exception
{
    //save important app data
    [self validateAndSaveCriticalApplicationData];
    
    
    
    //save crash log
    [self saveCrashLog:[NSString stringWithFormat:NSLocalizedString(@"Debug details follow:\n%@\n%@", nil),
                        [exception reason],
                        [[exception userInfo] objectForKey:HZUncaughtExceptionHandlerAddressesKey]]];
    
}

#pragma mark 日志 异常 工具方法

//记录console输出日志
- (void)startSaveConsoleLogs {
    
    fflush(stderr);
    dup2(dup(STDERR_FILENO), STDERR_FILENO);
    close(dup(STDERR_FILENO));
    
    freopen([kHZCrashConsoleLogFilePath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
}

//弹窗提示用户app已经崩
- (void)alertCrashException:(NSException *)exception{
    //弹窗提示用户app已经崩了
    UIAlertView *alert =
    [[UIAlertView alloc]
     initWithTitle:NSLocalizedString(@"Unhandled exception", nil)
     message:[NSString stringWithFormat:NSLocalizedString(
                                                          @"You can try to continue but the application may be unstable.\n\n"
                                                          @"Debug details follow:\n%@\n%@", nil),
              [exception reason],
              [[exception userInfo] objectForKey:HZUncaughtExceptionHandlerAddressesKey]]
     delegate:self
     cancelButtonTitle:NSLocalizedString(@"Quit", nil)
     otherButtonTitles:NSLocalizedString(@"Continue", nil), nil];
    [alert show];
}

//可以让程序继续运行，以保证交互，但不建议这么做
- (void)appContinueRun:(NSException *)exception{
    //保持线程继续运行
    CFRunLoopRef runLoop = CFRunLoopGetCurrent();
    CFArrayRef allModes = CFRunLoopCopyAllModes(runLoop);
    
    for (NSString *mode in (__bridge NSArray *)allModes)
    {
        NSLog(@"%@\n" ,mode);
    }
    
    while (!dismissed)
    {
        for (NSString *mode in (__bridge NSArray *)allModes)
        {
            CFRunLoopRunInMode((CFStringRef)mode, 0.001, false);
        }
    }
    
    CFRelease(allModes);
    
    NSSetUncaughtExceptionHandler(NULL);
    signal(SIGABRT, SIG_DFL);
    signal(SIGILL, SIG_DFL);
    signal(SIGSEGV, SIG_DFL);
    signal(SIGFPE, SIG_DFL);
    signal(SIGBUS, SIG_DFL);
    signal(SIGPIPE, SIG_DFL);
    
    if ([[exception name] isEqual:HZUncaughtExceptionHandlerSignalExceptionName])
    {
        kill(getpid(), [[[exception userInfo] objectForKey:HZUncaughtExceptionHandlerSignalKey] intValue]);
    }
    else
    {
        [exception raise];
    }
    
}

//保存重要的数据
- (void)validateAndSaveCriticalApplicationData
{
    
}

//记录crash log数据
- (void)saveCrashLog:(NSString *)logs{
    
    NSFileManager * fileManager = [[NSFileManager alloc] init];
    
    NSError *error = nil;
    NSLog(@"%@",kCrashLogFilePath);
    
    if ([fileManager fileExistsAtPath:kHZCrashLogFilePath]) {
        
        [fileManager createFileAtPath:kHZCrashLogFilePath contents:[logs  dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
    }else{
        
        [fileManager removeItemAtPath:kHZCrashLogFilePath error:&error];
        [fileManager createFileAtPath:kHZCrashLogFilePath contents:[logs  dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
    }
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)anAlertView clickedButtonAtIndex:(NSInteger)anIndex
{
    if (anIndex == 0)
    {
        dismissed = YES;
    }
}

@end

void HandleException(NSException *exception)
{
    printf("uncatch exception handler run\n");
    int32_t exceptionCount = OSAtomicIncrement32(&HZUncaughtExceptionCount);
    if (exceptionCount > HZUncaughtExceptionMaximum)
    {
        return;
    }
    
    //read crash starck infomation
    NSArray *callStack = [HZUnCatchExceptionHandler backtrace];
    NSMutableDictionary *userInfo =
    [NSMutableDictionary dictionaryWithDictionary:[exception userInfo]];
    [userInfo
     setObject:callStack
     forKey:HZUncaughtExceptionHandlerAddressesKey];
    
    //handler this exception
    [[[HZUnCatchExceptionHandler alloc] init]
     performSelectorOnMainThread:@selector(handleException:)
     withObject:
     [NSException
      exceptionWithName:[exception name]
      reason:[exception reason]
      userInfo:userInfo]
     waitUntilDone:YES];
}

void SignalHandler(int signal)
{
    printf("signal handler run\n");
    int32_t exceptionCount = OSAtomicIncrement32(&HZUncaughtExceptionCount);
    if (exceptionCount > HZUncaughtExceptionMaximum)
    {
        return;
    }
    
    //交给HandleException处理
    NSMutableDictionary *userInfo =
    [NSMutableDictionary
     dictionaryWithObject:[NSNumber numberWithInt:signal]
     forKey:HZUncaughtExceptionHandlerSignalKey];
    
    NSArray *callStack = [HZUnCatchExceptionHandler backtrace];
    [userInfo
     setObject:callStack
     forKey:HZUncaughtExceptionHandlerAddressesKey];
    
    [[[HZUnCatchExceptionHandler alloc] init]
     performSelectorOnMainThread:@selector(handleException:)
     withObject:
     [NSException
      exceptionWithName:HZUncaughtExceptionHandlerSignalExceptionName
      reason:
      [NSString stringWithFormat:
       NSLocalizedString(@"Signal %d was raised.", nil),
       signal]
      userInfo:
      [NSDictionary
       dictionaryWithObject:[NSNumber numberWithInt:signal]
       forKey:HZUncaughtExceptionHandlerSignalKey]]
     waitUntilDone:YES];
}

void InstallUncaughtExceptionHandler(void)
{
    NSSetUncaughtExceptionHandler(&HandleException);
    signal(SIGABRT, SignalHandler);
    signal(SIGILL, SignalHandler);
    signal(SIGSEGV, SignalHandler);
    signal(SIGFPE, SignalHandler);
    signal(SIGBUS, SignalHandler);
    signal(SIGPIPE, SignalHandler);
}

